var PlayBackOCX;
var SUCCESS = 0; /* 控件操作成功 */
var FAILED = 1; /* 控件操作失败 */
var DOWNLOADFLAG = 0;
var handle = "";
var theme = "Red";
var downloadDialog;
var settingDialog;
var Request = new Object();

function getParmXml(picType, picPath, videoSize, videoPath, decode) {
	var xml = [];

	xml.push("<?xml version=\"1.0\" encoding=\"utf-8\"?><global>");
	xml.push("<snap picture=\"" + picType + "\" save=\"" + picPath + "\"/>");
	xml.push("<record packSize=\"" + videoSize + "\" save=\"" + videoPath
			+ "\"/>");
	xml.push(" <performance decode=\"" + decode + "\"/>");
	xml.push("</global>");
	return xml.join("");
}
function initParam(isTrue) {
    $.ajax({
        type: "post",
        url: "../hkws/param/getParmAction",
        dataType: "json",
        headers: {
            Authorization: Request["token"]
        },
        success: function (data) {
            // var param=jQuery.parseJSON(data);
            var param = data
            // console.log(param)
            $("input[data-value='" + param.picType + "']").attr("checked", "checked");
            $("#captureSavePath").val(param.picPath);
            $("select option[value='" + param.videoSize + "']").attr("selected", "selected");
            // $("Select").uniform();
            $("#videoClibsSavePath").val(param.videoPath);
            $("#slideValue").text(param.decode);
            $("#slide").slider({value: param.decode});
            if (isTrue) {
                var xml = getParmXml(param.picType, param.picPath, param.videoSize, param.videoPath, param.decode);
                if (PlayBackOCX.setGlobalParam(xml) == FAILED) {
                    // JAlert("全局参数初始化失败 <a href='http://122.227.217.10:90/download/WebCtrl_V4.1.exe'></a>>","","")
                    if(!document.documentMode){
                        jAlert("视频控件初始化失败,请使用IE浏览器或360浏览器兼容模式打开");
                    }else{
                        tipsDialog.dialog("open");
                    }
                } else {
                    // setOpration()
                }
            } else {
                settingDialog.dialog("open");
            }
        }
    });
}
// 显示参数设置dialog
function paramset() {
	initParam(false);
	return false;
}
function downloadState(lparam, wparam) {
	// var percent = wparam.getElementsByTagName("download");
	print("句柄为：" + lparam + "下载状态：" + wparam);
}
function windowChange() {
	print("事件通知：窗口选中改变");
}

function startPlayback() {
	print("事件通知：回放开始");
}

function stopPlayback() {
	print("事件通知：回放停止");
}
function selectOcxSkinType() {
	var theme = $("#ocxSkinSelect").val();
	var ocxType = "playbackOcx";
	$.ajax({
		type : "post",
		url : "../../../param/setOcxSkinAction",
		dataType : "text",
		data : {
			theme : theme,
			ocxType : ocxType
		},
		success : function(data) {
			window.location.href = window.location.href;
		}
	});
	window.location.href = window.location.href;
}

// 选择窗口布局
function selectWindowType() {
	var layoutType = Number($("#windowTypeSelect").val());
	if (PlayBackOCX.SetFitLayout(layoutType) != SUCCESS) {
		jAlert('窗口布局设置失败', '窗口布局', 'error');
	} else {
		print("窗口布局设置成功");
	}
}

//抓图完成事件通知
function picCutEvent(param) {
    var windIndex = PlayBackOCX.getSelectedWindow();
    if (param == SUCCESS) {
        $.ajax({
            type: "post",
            url: "../hkws/param/getParmAction",
            dataType: "json",
            headers: {
                Authorization: Request["token"]
            },
            success: function (data) {
                var param = data
                jAlert('抓图成功，图片已保存至：' + param.picPath, '提示', 'ok');
            }
        });
        print("窗口" + windIndex + "：抓图成功");
    } else {
        jAlert('抓图失败', '提示', 'error');

        print("窗口" + windIndex + "：抓图失败");
    }
    // settingDialog.dialog("open");
}

//录像完成事件通知
function videoCutEvent(param) {
    var windIndex = PlayBackOCX.getSelectedWindow();
    if (param == SUCCESS) {
        $.ajax({
            type: "post",
            url: "../hkws/param/getParmAction",
            dataType: "json",
            headers: {Authorization: Request["token"]},
            success: function (data) {
                var param = data
                jAlert('录像成功，视频已保存至：' + param.videoPath, '提示', 'ok');
            }
        });
        print("窗口" + windIndex + "：录像成功");
    } else {
        print("窗口" + windIndex + "：录像失败");
        jAlert('录像失败', '提示', 'error');
    }
    // settingDialog.dialog("open");
}

function applyToken(reqID) {
    $.ajax({
        url: "../hkws/token",
        type: "get",
        dataType: "json",
        headers: {
            Authorization: Request["token"]
        },
        success: function (token) {
            var setTokenResult = PlayBackOCX.setToken(reqID, token.resultData);
            if (setTokenResult == SUCCESS) {
                print("token设置成功");
            } else {
                print("token设置失败，错误码为：" + setTokenResult)
            }
        }
    });
}

//跳转回放
function realtimeplayHtml() {
    if(!Request["indexCode"]){
        this.window.location = "video.html" + location.search;
    }
    // this.window.location = "playback.html?query=deviceId:5c413f5e0b17054314ff71c5;_;token:Bearer%20eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MzYwMTU1MDE5MjYxNCwiaWF0IjoxNTUwMTkyNjE0LCJqdGkiOiI4MGRmOCJ9.1ukmRoRQV7oELnvqr9n9Pngey_RCUVLoUrIqmlSGg3zWBjYCGqop2lWg1FZbJG4EyINLqqsvww15K6snuWB6wg";
}

$(document).ready(
		function() {
            var url = location.search;
            if (url.indexOf("?") != -1) {
                var str = url.substr(1)　//去掉?号
                var strs = str.split("&");
                for (var i = 0; i < strs.length; i++) {
                    var query = strs[i].split("=")[1];
                    strs = query.split(";_;");
                    for (var i = 0; i < strs.length; i++) {
                        Request[strs[i].split(":")[0]] = unescape(strs[i].split(":")[1]);
                    }
                }
            }

			// 参数设置dialog
			settingDialog = $('#settingDialog').dialog({
				autoOpen : false,
				modal : true,
				width : 600,
				height : 500,
				draggable : true,
				buttons : {
					"ok" : {
						text : '确认',
						'class' : 'bPrimary',
						click : function(dialog) {
							dialog.close();
							saveParam();
						}
					},
					"cancel" : {
						text : '关闭',
						click : function(dialog) {
							dialog.close();
						}
					}
				}
			});

            var tipsDialog = $('#tips').dialog({
                autoOpen: false,
                modal: true,
                width: 300,
                height: 200,
                draggable: true,
                buttons: {
                    "cancel": {
                        text: '关闭',
                        'class': 'bPrimary',
                        click: function (dialog) {
                            dialog.close();
                        }
                    }
                }
            });

			downloadDialog = $('#downloadDialog').dialog({
				autoOpen : false,
				modal : true,
				width : 600,
				height : 500,
				draggable : true,
				buttons : {
					"ok" : {
						text : '确认',
						'class' : 'bPrimary',
						click : function(dialog) {
							dialog.close();
							downloadVideo();
						}
					},
					"cancel" : {
						text : '关闭',
						click : function(dialog) {
							dialog.close();
						}
					}
				}
			});

			/* 查询录像和回放——开始 */
			var myDate = new Date().format("yyyy-MM-dd");
			$("#beginTime").val(myDate + " 00:00:00");
			$("#endTime").val(myDate + " 23:59:59");

			$("#playCramera_time").click(function() {

				var indexCode = $("#selectCameraName").attr("indexCode");
				if (indexCode == null) {
					$.sticky("请选择监控点！", 'attention');
					return;
				}
				playCamera(indexCode);
			});

			function playCamera(indexCode) {
				var beginTime = $("#beginTime").val();
				var endTime = $("#endTime").val();

				if (beginTime == "") {
					$.sticky("开始时间不能为空！", 'attention');
					return;
				}
				if (endTime == "") {
					$.sticky("结束时间不能为空！", 'attention');
					return;
				}
				var subTime = (toDate(endTime).getTime() - toDate(beginTime)
						.getTime()) / 1000 / 3600 / 24;
				// 比较日期大小
				if (subTime < 0) {
					$.sticky("开始时间必须小于结束时间！", "时间选择错误！", 'attention');
					return;
				}
				if (subTime > 3) {
					$.sticky("时间跨度不得超过3天，请重新选择！", "时间选择错误！", 'attention');
					return;
				}
				var storeType = $("#storeType").val();
				beginTime = formatDate(beginTime);
				endTime = formatDate(endTime);

				// 获取回放xml
                $.post("../hkws/camera/playback/stream", {
                    indexCode: indexCode,
                    beginTime: beginTime,
                    endTime: endTime,
                    storeType: storeType
                }, function (data, status) {
                    // alert(data);
                    var playBackResult = PlayBackOCX.setPlayback(beginTime,
                        endTime, data);
                    if (playBackResult == SUCCESS) {
                        print("查询成功");
                    } else {
                        print("查询失败，错误码为：" + playBackResult);
                    }
                }, "text", {Authorization: Request["token"]});
            }

			// 下载设置
			$('#downloadVideo').click(function() {
				if (DOWNLOADFLAG == 0) {
					var indexCode = $("#selectCameraName").attr("indexCode");
					if (indexCode == null) {
						$.sticky("请选择监控点！", 'attention');
						return;
					}
					downloadDialog.dialog("open");
				} else if (DOWNLOADFLAG == 1) {
					var result = PlayBackOCX.stopDownload(handle);
					DOWNLOADFLAG = 0;
					var message = ""
					$("#downloadVideo").text('开始下载');
					if (result == 0) {
						message = "停止下载成功";
					} else {
						message = "停止下载失败";
					}
					print(message);
				}
				return false;
			});

			// 获取当前窗口
			$("#getSelectedWindow").click(function() {
				var playBackResult = PlayBackOCX.getSelectedWindow();
				print("当前窗口为：" + playBackResult);
			});

			// 停止当前窗口回放
			$("#stopPlayback").click(function() {
				PlayBackOCX.stopPlayback(PlayBackOCX.getSelectedWindow());
			});

			// 获取解码时间
			$("#getDecodeTime").click(
					function() {
						var result = PlayBackOCX.getDecodeTime(PlayBackOCX
								.getSelectedWindow());

						print("当前时间为：" + result);
					});

			// 停止所有回放
			$("#stopPlaybackAll").click(function() {
				PlayBackOCX.stopPlayback(-1);
			});

			// 清空提示框
			$("#clearAll").click(function() {
				$("#information").val("");
			});
			getOcxSkin();
            // initParam(true)
		});

// 获取空间主题
function getOcxSkin() {
	var ocxType = "playbackOcx";
	$.ajax({
				type : "post",
				url : "../../hkws/param/getOcxSkinAction",
				dataType : "text",
				headers: {
					Authorization: Request["token"]
				},
				data : {
					ocxType : ocxType
				},
				success : function(data) {
					theme = data;
					var options = {
						divId : "ocx_playback",
						theme : theme
					};
					PlayBackOCX = new PlaybackOCX(options);
					PlayBackOCX.registerCallback(PLAYBACK_EVENT_WINDOW,
							windowChange);
					PlayBackOCX.registerCallback(PLAYBACK_EVENT_START,
							startPlayback);
					PlayBackOCX.registerCallback(PLAYBACK_EVENT_STOP,
							stopPlayback);
					PlayBackOCX.registerCallback(PLAYBACK_EVENT_TOKEN,
							applyToken);
					PlayBackOCX.registerCallback(EVENT_DOWNLOAD, downloadState);
					PlayBackOCX.registerCallback(MPB_OCX_MSG_SNAP_DONE, picCutEvent);
                    PlayBackOCX.registerCallback(MPB_OCX_MSG_CLIP_DONE, videoCutEvent);
                    initParam(true)
				}
			});
}

// 下载录像
function downloadVideo() {

	var beginTime = $("#beginTime").val();
	var endTime = $("#endTime").val();
	var indexCode = $("#selectCameraName").attr("indexCode");
	if (indexCode == null) {
		$.sticky("请选择监控点！", 'attention');
		return;
	}
	if (beginTime == "") {
		$.sticky("开始时间不能为空！", 'attention');
		return;
	}
	if (endTime == "") {
		$.sticky("结束时间不能为空！", 'attention');
		return;
	}
	var subTime = (toDate(endTime).getTime() - toDate(beginTime).getTime()) / 1000 / 3600 / 24;
	// 比较日期大小
	if (subTime < 0) {
		$.sticky("开始时间必须小于结束时间！", "时间选择错误！", 'attention');
		return;
	}
	if (subTime > 3) {
		$.sticky("时间跨度不得超过3天，请重新选择！", "时间选择错误！", 'attention');
		return;
	}
	var storeType = $("#storeType").val();
	beginTime = formatDate(beginTime);
	endTime = formatDate(endTime);
	var filePath = $("#videoSavePath").val();
	var indexCode = $("#selectCameraName").attr("indexCode");
	$.post("../../../stream/getPlaybackInfoAction", {
		indexCode : indexCode,
		beginTime : beginTime,
		endTime : endTime,
		storeType : storeType
	}, function(data, status) {
		var playBackResult = PlayBackOCX.setPlayback(beginTime, endTime, data);
		if (playBackResult == SUCCESS) {
			alert("查询成功,开始下载");
			var result = PlayBackOCX.startDownLoad(beginTime, endTime,
					filePath, data,isHttps);
			if (result == 1) {
				print("调用下载接口失败");
			} else {
				DOWNLOADFLAG = 1;
				$("#downloadVideo").text('停止下载');
				handle = result;
				print("下载成功，句柄为" + result);
			}
		} else {
			print("查询失败，错误码为：" + playBackResult);
		}
	}, "text");

}

// 保存全局参数
function saveParam() {
	var pictype = $("input[name='capture.format']:checked").attr("data-value");
	var picpath = $("#captureSavePath").val();
	var videosize = $("#videoClibsSize").val();
	var videopath = $("#videoClibsSavePath").val();
	var decode = $("#slideValue").text();
	var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><global><snap picture=\""
			+ pictype
			+ "\" save=\""
			+ picpath
			+ "\"/><clip packSize=\""
			+ videosize
			+ "\" save=\""
			+ videopath
			+ "\"/><performance decode=\"" + decode + "\"/></global>";
	if (PlayBackOCX.setGlobalParam(xml) == SUCCESS) {
		$.ajax({
			type : "post",
			url : "../../../param/saveParmAction",
			dataType : "text",
			data : {
				picType : pictype,
				picPath : picpath,
				videoSize : videosize,
				videoPath : videopath,
				decode : decode
			}
		});
		jAlert('全局参数设置成功', '全局参数', 'ok');
	} else {
		jAlert('全局参数设置失败', '全局参数', 'error');
	}

}

// 用于切换参数设置表单里的页面
function showDetail(e) {
	var name = $(e).attr('name');
	var id = $(e).attr('id');
	$("a[name='" + name + "']").parent().removeClass('active');
	$(".form-inline").addClass('div-none');
	$(e).parent().addClass("active");
	$("#" + id + name).removeClass('div-none');
}

// 用于设置抓图和剪辑的保存路径
function browseFolder(id) {
	try {
		var Message = "选择文件路径"; // 选择框提示信息
		var Shell = new ActiveXObject("Shell.Application");
		// var Folder = Shell.BrowseForFolder(0, Message, 64, 17); //起始目录为：我的电脑
		var Folder = Shell.BrowseForFolder(0, Message, 0); // 起始目录为：桌面
		if (Folder != null) {
			document.getElementById(id).value = Folder.self.path;
			return Folder;
		}
	} catch (e) {
		jAlert(e.message);
	}
}

// 用于参数设置表单里的解码性能
$('#slide').slider({
	range : "min",
	min : 1,
	max : 9,
	value : 5,
	slide : function(event, ui) {
		$('#slideValue').text(ui.value);
	}
});
/* 参数设置——结束 */

function toDate(strDateTime) {
	var strDateTimes = strDateTime.split(' ');
	var strDate = strDateTimes[0].split('-');
	var year = Number(strDate[0]);
	var month = Number(strDate[1]) - 1;
	var day = Number(strDate[2]);
	var strTime = strDateTimes[1].split(':');
	var hour = Number(strTime[0]);
	var minute = Number(strTime[1]);
	var secend = Number(strTime[2]);
	return new Date(year, month, day, hour, minute, secend);
}

function formatDate(time) {
	return time.replace(" ", "T") + "Z";
}
/* 查询录像和回放——结束 */

$(function() {
    var url1,url2;
    if(Request["deviceId"]){
        url1 = "../hkws/cameras/org/ZTree/device/" + Request["deviceId"];
        // url2 = "../hkws/camera/playback/stream/list/" + Request["deviceId"];
    } else if(Request["indexCode"]){
        url1 = "../hkws/cameras/org/ZTree/indexCode/" + Request["indexCode"];
        // url2 = "../hkws/camera/stream/" + Request["indexCode"];
    }

    // if(url2 && Request["beginTime"] && Request["endTime"]){
    //     // 获取回放xml
    //     $.post(url2, {
    //         beginTime: Request["beginTime"],
    //         endTime: Request["endTime"],
    //         storeType: 0
    //     }, function (data, status) {
    //         var xmlList = data.resultData;
    //         for (var i in xmlList) {
    //             var winIndex = PlayBackOCX.getSelectedWindow();
    //             var playBackResult = PlayBackOCX.setPlayback(Request["beginTime"],
    //                 Request["endTime"], xmlList[i]);
    //             if (playBackResult == SUCCESS) {
    //                 // $('#zTreea_id_' + i + '_ico').attr('class', 'button ico m-gun-playing_ico_docu')
    //                 // updatePlayPauseIcon(winIndex, {treeId:i,play:true});
	//
    //                 if (PlayBackOCX.setSelectedWindow(winIndex + 1) == -1) {
    //                     PlayBackOCX.setSelectedWindow(0);
    //                 }
    //             }
    //             // indexcodes[winIndex] = "001077";
    //             // ids[winIndex] = i;
    //         }
    //     }, "json", {Authorization: Request["token"]});
	// }

    //ztree
    var settingRes = {
        //页面加载时先获取组织资源
        ajax: {
            // url: "../hkws/resource/ZTree/1000",
            url: url1,
            headers: {
                Authorization: Request["token"]
            },
            // url: "../hkws/org/camera/ZTree/001082",
            type: "post",
            // contentType: "application/json; charset=utf-8",
            // data : ["001799","001592"],
            // data : {
            //     indexCodes : ["001799","001592"]
            // },
            dataType: "json"
        },
        data: {
            simpleData: {
                enable: true
            },
            key: {
                name: "name"
            }
        },
        //事件回调
        callback: {
            beforeExpand: zTreeBeforeExpand,
            onDblClick: onclick
        }
    };

	// 处理监控点节点的id属性，在每个监控点的id属性值前面加上 "camera"
	function filter(treeId, parentNode, childNodes) {
		if (!childNodes)
			return null;
		for (var i = 0, l = childNodes.length; i < l; i++) {
			childNodes[i].id = "camera" + childNodes[i].id;
		}
		return childNodes;
	}

	function zTreeBeforeExpand(treeId, treeNode) {
		var treea = $("#zTreea").tree();
		if (!treeNode.isExpand) {
			treea.reAsyncChildNodes(treeNode, "!refresh");
			treeNode.isExpand = 1;
		}
		return true;
	}
	;

	function onclick(event, treeId, treeNode) {
		if (treeNode.tag == "camera") {
			$("#selectCameraName").text(treeNode.name);
			$("#selectCameraName").attr({
				"indexCode" : treeNode.indexCode
			});
		}
	}

	$('#zTreea').tree(settingRes);
})
/* 视频回放页面监控点资源树 */

function print(msg) {
	// var console = document.getElementById('information');
	// var oldMsg = console.value;
	// console.value = oldMsg + '\n' + msg;
	// console.log(msg)
}
